<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <el-dialog v-model="dialogVisible" title="导入文件" width="500" :before-close="closeDialog">
    <el-form :model="dialogFormData" :rules="formRules">
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="dialogFormData.fileType" placeholder="请选择" clearable @change="handleTypeChange">
          <el-option v-for="dict in fileTypes" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="dialogFormData.fileType" label="文件格式" prop="fileFormat">
        <el-select v-model="dialogFormData.fileFormat" placeholder="请选择" clearable>
          <el-option v-for="dict in inputModelTypes" :key="dict.value" :label="dict" :value="dict" />
        </el-select>
      </el-form-item>
    </el-form>
    <template v-if="dialogFormData.fileFormat">
      <div class="b-1 b-#cccccc b-solid p2 mb10">
        <el-scrollbar style="height: 300px">
          <div v-for="(item, index) in fileList" :key="'file' + index" class="flex line-height-5">
            <div class="w700">{{ item.name }}</div>
            <div class="w150">{{ getSizeStr(item.size) }}</div>
            <div class="w100" @click="handleDelete(index)">
              <el-icon><Close /></el-icon>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="flex flex-justify-between">
        <el-upload
          v-model:file-list="fileList"
          :show-file-list="false"
          action="#"
          multiple
          :on-exceed="handleExceed"
          :limit="limit"
          :auto-upload="false"
        >
          <el-button type="primary">选择上传文件</el-button>
        </el-upload>
        <div class="">已经选择{{ fileList.length }}条数据</div>
      </div>
    </template>
    <div class="create mt10">
      <span>创建人：{{ dialogFormData.createBy }}</span>
      <span class="ml8">创建时间：{{ dialogFormData.createTime }}</span>
    </div>
    <template #footer>
      <div class="dialog-footer text-center">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="sureDialog">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="ImportFileDialog" lang="ts">
import useUserStore from '@/store/modules/user';
import { parseTime } from '@/utils/ruoyi';
import { types } from '@/api/caxDataConversionMajorComponent/index';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { sourceFileUpload } from '@/api/caxDataConversionMajorComponent/fileManagement/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['call-back']);
const dialogVisible = ref(false);
const userStore = useUserStore();
const dialogFormData = reactive({
  fileType: '',
  fileFormat: '',
  createBy: userStore.nickname,
  createTime: parseTime(new Date())
});
let intervalId = null;
const fileList = ref([]);
const updateTime = () => {
  dialogFormData.createTime = parseTime(new Date());
};
const fileTypes = ref(types);
const limit = ref(30);
const inputModelTypes = ref([]);
const formRules = ref<ElFormRules>({
  fileType: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
  fileFormat: [{ required: true, message: '文件格式不能为空', trigger: 'change' }],
  file: [{ required: true, message: '文件不能为空', trigger: 'change' }]
});
const openDialog = (num?) => {
  if (num) {
    limit.value = num;
  }
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`当前限制${limit.value}, 你选择了这次选择了 ${files.length} 个文件, 共选择了${files.length + uploadFiles.length}文件`);
};
const handleTypeChange = () => {
  if (dialogFormData.fileType) {
    const obj = fileTypes.value.find((item) => item.value === dialogFormData.fileType);
    if (obj) {
      inputModelTypes.value = obj.inputType;
      return;
    }
  }
  let arr = [];
  fileTypes.value.forEach((element) => {
    arr = [...arr, ...element.inputType];
  });
  inputModelTypes.value = arr;
};
const checkFile = () => {
  for (let i = 0; i < fileList.value.length; i++) {
    const name = fileList.value[i].name;
    const type = name.substring(name.lastIndexOf('.')).toLocaleLowerCase();
    const fileFormat = '.' + dialogFormData.fileFormat.toLocaleLowerCase();
    if (type !== fileFormat) {
      proxy?.$modal.msgError(`限制上传${dialogFormData.fileFormat}类型文件`);
      return false;
    }
  }
  return true;
};
const getSizeStr = (size) => {
  if (size < 1024) {
    return size + 'B';
  } else if (size > 1023 && size < 1024 * 1024) {
    return Number(size / 1024).toFixed(2) + 'kB';
  } else {
    return Number(size / 1024 / 1024).toFixed(2) + 'MB';
  }
};
const sureDialog = async () => {
  if (!fileList.value.length) {
    proxy?.$modal.msgError(`请上传文件`);
    return false;
  }
  if (!checkFile()) {
    return false;
  }
  const formData = new FormData();
  formData.append('type', dialogFormData.fileType);
  fileList.value.forEach((item) => {
    formData.append('files', item.raw);
  });
  await sourceFileUpload(formData);
  closeDialog();
  proxy?.$modal.msgSuccess(`新增文件成功！`);
  emit('call-back');
};
const handleDelete = async (index) => {
  await proxy?.$modal.confirm('是否确认删除选择数据！');
  fileList.value.splice(index, 1);
};
onMounted(() => {
  // 每秒更新一次时间
  intervalId = setInterval(updateTime, 1000);
});

onUnmounted(() => {
  // 清除定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
});
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped></style>
